<template>
  <el-dialog title="添加广告文件" @close="closePop" :visible.sync="isShow" width="750" :lock-scroll=false @open="openDialog">
    <div v-loading="loading">
      <el-card>
        <el-form :rules="rules" :model="form" ref="form" size="mini" label-width="90px">
          <el-row :gutter="40">
            <el-col :span='10'>
              <el-form-item label="图片上传" prop="file">
                <el-upload :disabled="disabled" class="ADupload avatar-uploader" :action=fileUploadUrl :show-file-list="false"
                  :before-upload="handleBeforeUpload" :on-progress="handleProgress" :on-error="handleRemove"
                  :on-success="handleSuccess" ref="upload">
                  <img v-if="imageUrl && !disabled" :src="fileDownloadUrl + imageUrl" class="avatar">
                  <i v-if="!imageUrl && !disabled" class="el-icon-plus avatar-uploader-icon"></i>
                  <i v-if="form.adType =='V' && isUpload" class="el-icon-check avatar-uploader-icon"></i>
                  <!-- <i v-if="disabled" class="el-icon-close avatar-uploader-icon"></i> -->
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span='14'>
              <el-form-item label="机构编号:" prop='brno'>
                <el-select v-model="form.brno" :disabled="option.isDisabled" filterable placeholder="请选择机构编号">
                  <el-option v-for="item in branchList" :key="item.orgno" :label="item.orgno+'-'+item.cname" :value="item.orgno"
                    :disabled="item.disabled">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span='14'>
              <el-form-item label="广告编号" prop="adNo">
                <el-input v-model="form.adNo" placeholder="请输入广告编号" :disabled="finishUp" @blur="adNoCheck"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span='14'>
              <el-form-item label="广告名称" prop="adName">
                <el-input v-model="form.adName" placeholder="请输入广告名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span='14'>
              <el-form-item label="广告类型" prop="adType" placeholder="请选择广告类型">
                <el-select v-model="form.adType">
                  <el-option v-for="item in adTypeList" :key="item.value" :label="item.label" :value="item.value"
                    :disabled="item.disabled">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span='24'>
              <el-form-item label="广告内容" prop="imageUrl" v-if="disabled">
                <el-input v-model="form.imageUrl" placeholder="请输入广告内容"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span='24'>
              <el-form-item label="是否启用" prop="isEnable">
                <el-radio-group v-model="form.isEnable">
                  <el-radio :label=true>启用</el-radio>
                  <el-radio :label=false>不启用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span='24'>
              <el-form-item label="播放日期" required>
                <el-col :span="11">
                  <el-form-item prop="startDate" style="margin-bottom:0 !important;">
                    <el-date-picker style="width: 100%;" :editable="false" value-format="yyyyMMdd" v-model="form.startDate"
                      type="date" placeholder="播放开始日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="2" style="text-align:center;">
                  -
                </el-col>
                <el-col :span="11">
                  <el-form-item prop="endDate" style="margin-bottom:0 !important;">
                    <el-date-picker style="width: 100%;" :editable="false" value-format="yyyyMMdd" v-model="form.endDate"
                      type="date" placeholder="播放结束日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
            <el-col :span='24'>
              <el-form-item label="播放时间" required>
                <el-col :span="11">
                  <el-form-item prop="startTime" style="margin-bottom:0 !important;">
                    <el-time-picker style="width: 100%;" :editable="false" value-format="HHmmss" v-model="form.startTime"
                      placeholder="播放开始时间">
                    </el-time-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="2" style="text-align:center;">
                  -
                </el-col>
                <el-col :span="11">
                  <el-form-item prop="endTime" style="margin-bottom:0 !important;">
                    <el-time-picker style="width: 100%;" :editable="false" value-format="HHmmss" v-model="form.endTime"
                      placeholder="播放结束时间">
                    </el-time-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span='24'>
              <el-form-item label="备注" prop="fileDesc">
                <el-input v-model="form.fileDesc" placeholder="请输入备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" @click="closePop">取 消</el-button>
      <el-button size="small" type="primary" @click="submitForm('form')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import getGlobalParams from "@/common/utils/getGlobalParams";

  import request from "@/common/utils/request";
  import branchList from "@/message/shared/branch-list"; //机构号
  import adUploadIns from "@/message/resourceManage/advertising/ad-upload-upload";
  import adUploadTableIns from "@/message/resourceManage/advertising/ad-upload-editShow";


  export default {
    props: {
      option: Object
    },
    data() {
      return {
        //公共
        loading: false,
        isUpload: false,
        //上传
        finishUp: false,
        fileList: [],
        branchList: [],
        adTypeList: [{
          "value": "P",
          "label": "图片"
        }, {
          "value": "V",
          "label": "视频"
        }, {
          "value": "C",
          "label": "文字"
        }],
        adTypeMap: {},
        imageUrl: "",
        fileUploadUrl: "",
        fileDownloadUrl: "",
        fileUploadUrl1: "",
        disabled: false,
        //表格查询
        form: {
          startDate: "",
          endDate: "",
          startTime: "000000",
          endTime: "235959",
          isEnable: true,
          fileDesc: "",
          adNo: "",
          adName: "",
          adType: "P",
          imageUrl: "",
          brno: ""
        },
        //弹窗
        dialogFormVisible: false,

        //校验
        rules: { //file fileDesc isEnable startDate endDate startTime endTime
          file: [{
              trigger: "blur",
              validator: this.picVali
            },
            // { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
          ],
          adNo: [{
              required: true,
              message: "请输入广告编号",
              trigger: "blur"
            },
            {
              max: 10,
              message: "长度不超过10个字符",
              trigger: "blur"
            }
          ],
          imageUrl: [{
            required: true,
            message: "广告内容不能为空",
            trigger: "blur"
          }],
          adName: [{
              required: true,
              message: "请输入广告名称",
              trigger: "blur"
            },
            {
              max: 30,
              message: "长度不超过30个字符",
              trigger: "blur"
            }
          ],
          fileDesc: [{
            max: 50,
            message: "长度不超过50个字符",
            trigger: "blur"
          }],
          isEnable: [{
            required: true,
            message: "请选择是否启用",
            trigger: "blur"
          }],
          brno: [{
            required: true,
            message: "请选择机构编号",
            trigger: "change"
          }],
          adType: [{
            required: true,
            message: "请选择广告类型",
            trigger: "change"
          }],
          startDate: [{
              required: true,
              message: "请选择起始日期",
              trigger: "change"
            },
            {
              trigger: "change",
              validator: this.startDateVali
            }
          ],
          endDate: [{
              required: true,
              message: "请输入结束日期",
              trigger: "change"
            },
            {
              trigger: "change",
              validator: this.endDateVali
            }
          ],
          startTime: [{
              required: true,
              message: "请输入起始时间",
              trigger: "change"
            },
            {
              trigger: "change",
              validator: this.startTimeVali
            }
          ],
          endTime: [{
              required: true,
              message: "请输入结束时间",
              trigger: "change"
            },
            {
              trigger: "change",
              validator: this.endTimeVali
            }
          ]
        },
      };
    },
    computed: {
      isShow: {
        get: function () {
          return this.option.isShow;
        },
        set: function (newVal) {
          this.option.isShow = newVal;
        }
      },
      pokerHistory() {
        return this.form.adType
      }
    },
    created() {
      this.fileUploadUrl1 = getGlobalParams.get("ADImgFileUploadAddress");
      this.fileDownloadUrl = getGlobalParams.get("ADImgFileDownloadAddress");
    },
    watch: {
      pokerHistory(val, oldVal) {
        this.isUpload = false;
        if (val == "C") {
          this.disabled = true;
          this.form.imageUrl = ""
        } else {
          this.disabled = false;
          this.imageUrl = ""
        }

      }
    },
    methods: {
      adNoCheck() {
        if(this.form.adNo == ''){
          return false
        }
        this.loading = true;
        let resBody = new adUploadTableIns();
        resBody.data.adNo = this.form.adNo;
        request(resBody)
          .then(response => {
            this.loading = false;
            if (response.SYS_HEAD.ReturnCode == "000000") {
              this.form.adNo = ""
              this.$message({
                type: "warning",
                message: `广告编号已存在!`
              });
            } else {
              this.finishUp = true ;
              this.fileUploadUrl = this.fileUploadUrl1 + "_" + this.form.adNo
            }
          })
      },
      openDialog() {
        let resBody = new branchList();
        resBody.data.orgno = this.$store.getters.BranchNum;
        request(resBody)
          .then(response => {
            if (response.SYS_HEAD.ReturnCode === "000000") {
              this.branchList = response.RspInfo.Result || []
            } else {
              this.$message({
                type: "warning",
                message: SYS_HEAD.ReturnMessage
              });
            }
          })
          .catch(error => {
            console.error("查询错误", error);
          });
      },
      closePop() {
        this.isShow = false;
        // console.log(this.$refs);
        this.$refs.form.resetFields(); //清除表单数据
        this.$refs.form.clearValidate(); //清除表单验证
        this.imageUrl = ""; //清除图片
        this.finishUp = false;
      },
      handleProgress(event, file, fileList) {
        // console.log(fileList);
      },
      handleBeforeUpload(file) {
        let result = false;
        this.$refs.form.validateField('adNo', valid =>{
          if (!valid) {
            this.loading = true;
            result = true
          }
        })
        return result
      },
      handleSuccess(event, file, fileList) {
          // console.log(fileList);
        if (this.form.adType == "V"){
          this.disabled = true;
          this.isUpload = true;
        }
        this.loading = false;
        this.imageUrl = this.form.adNo + "/" + file.name;
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`); /////////这里无效
      },
      handleRemove(file, fileList) {
        // console.log(file, fileList);
        this.imageUrl = "";
      },
      handlePreview(file) {},
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
        );
      },

      previewBanner(file) {
        let reader = new FileReader();
        reader.onload = () => {
          let _base64 = reader.result;
          doWhatUWant(_base64); //就可以做你想做的啦！！！
        };
        reader.readAsDataURL(file.raw);
      },

      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.queryUpload();
          } else {
            this.$message({
              type: "warning",
              message: "请按条件输入"
            });
            return false;
          }
        });
      },
      picVali(rule, value, callback) {
        if(this.form.adType != "C"){
          if (this.imageUrl == "") {
            callback("请选择上传图片");
          } else {
            callback();
          }
        }else {
            callback();
        }
      },
      startDateVali(rule, value, callback) {
        // console.log(this);
        if (this.form.endDate == "") {
          callback();
        } else if (value > this.form.endDate) {
          callback(new Error('起始日期不得大于结束日期'));
        } else {
          if (this.form.endDate !== '') {
            this.$refs.form.validateField('endDate');
          }
          callback();
        }
      },
      endDateVali(rule, value, callback) {
        if (value < this.form.startDate) {
          callback(new Error('结束日期不得小于开始日期'));
        } else {
          //加这句有死循环
          // if (this.form.startDate !== '') {
          //   this.$refs.form.validateField('startDate');
          // }
          callback();
        }
      },
      startTimeVali(rule, value, callback) {
        // console.log(this);
        if (this.form.endTime == "") {
          callback();
        } else if (value > this.form.endTime) {
          callback(new Error('起始时间不得大于结束时间'));
        } else {
          if (this.form.endTime !== '') {
            this.$refs.form.validateField('endTime');
          }
          callback();
        }
      },
      endTimeVali(rule, value, callback) {
        if (value < this.form.startTime) {
          callback(new Error('结束时间不得小于开始时间'));
        } else {
          callback();
        }
      },
      async queryUpload() {
        this.loading = true;
        let resBody = new adUploadIns();
        resBody.data.StartDate = this.form.startDate;
        resBody.data.EndDate = this.form.endDate;
        resBody.data.StartTime = this.form.startTime;
        resBody.data.EndTime = this.form.endTime;
        resBody.data.IsEnabled = !this.form.isEnable + 0 + ""; //0启用 1禁用
        if(this.form.adType == "C"){
          resBody.data.AdContent = this.form.imageUrl;
        } else {
          resBody.data.AdContent = this.imageUrl;
        }
        resBody.data.AdType = this.form.adType;
        resBody.data.AdNo = this.form.adNo;
        resBody.data.Brno = this.form.brno;
        resBody.data.AdName = this.form.adName;
        resBody.data.Remark = this.form.fileDesc;

        let response = await request(resBody);
        this.loading = false;
        if (response.SYS_HEAD.ReturnCode == "000000") {
          this.$emit('succ');
          this.isShow = false;
          //清空表格
          this.form = {
            startDate: "",
            endDate: "",
            startTime: "",
            endTime: "",
            isEnable: true,
            fileDesc: ""
          };
          this.fileList = [];
          this.$message({
            type: "success",
            message: "上传成功!"
          });
        } else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          });
        }
      },
    }
  };
</script>

<style lang="scss">
  .ADupload.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409EFF;
    }

    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
</style>
